using System;
using System.Windows.Forms;
using Timer = System.Windows.Forms.Timer;
using static TangLiveRecorder.Data;
using Microsoft.VisualBasic.Logging;

namespace TangLiveRecorder.Controls
{
    public partial class LogControl : UserControl, ITransient
    {
        private int logCounter = 0;

        public LogControl()
        {

            InitializeComponent();

            this.Tag = "Log";
            this.Dock = DockStyle.Fill;
            BindEvents();

            // 订阅日志事件
            LogAdded += LogControl_LogAdded;
            LogCleared += LogControl_LogCleared;

            // 初始化显示现有日志
            txtLogContent.Text = GetAllLogs();
            if (!string.IsNullOrEmpty(txtLogContent.Text))
            {
                txtLogContent.SelectionStart = txtLogContent.Text.Length;
                txtLogContent.ScrollToCaret();
            }
        }


        private void BindEvents()
        {
            btnClearLog.Click += BtnClearLog_Click;
        }



        // 处理日志添加事件
        private void LogControl_LogAdded(object sender, LogEventArgs e)
        {
            if (txtLogContent.InvokeRequired)
            {
                txtLogContent.Invoke(new Action(() => AppendLogToTextBox(e.LogMessage)));
            }
            else
            {
                AppendLogToTextBox(e.LogMessage);
            }
        }

        // 处理日志清空事件
        private void LogControl_LogCleared(object sender, EventArgs e)
        {
            if (txtLogContent.InvokeRequired)
            {
                txtLogContent.Invoke(new Action(() => txtLogContent.Clear()));
            }
            else
            {
                txtLogContent.Clear();
            }
        }

        // 追加日志到文本框
        private void AppendLogToTextBox(string logMessage)
        {
            txtLogContent.Text += logMessage + Environment.NewLine;
            txtLogContent.SelectionStart = txtLogContent.Text.Length;
            txtLogContent.ScrollToCaret();
        }

        private void BtnClearLog_Click(object sender, EventArgs e)
        {
            logCounter = 0;
            ClearLogs(); // 使用Data.Log类清空日志，会触发LogCleared事件
            AddLog("日志已清空"); // 添加一条新日志
        }

        // LimitLogLines方法已移除，日志行数限制由Data.Log类处理

        // 对外提供的添加日志方法，使用Data.Log类的方法
        public void AddLogMessage(string message)
        {
            AddLog(message); // 使用Data.Log类添加日志，会触发LogAdded事件
        }

        // 析构函数，取消事件订阅
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            if (disposing)
            {
                // 取消事件订阅
                LogAdded -= LogControl_LogAdded;
                LogCleared -= LogControl_LogCleared;

                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }


    }
}
